<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

/**
 *
 * 文件列表相关接口
 * @author Calvin<hongbinfu@163.com>
 * @readme  :返回结果请使用common_response
 * @help    :具体用法请参考https://github.com/chriskacerguis/codeigniter-restserver
 * @other   :
 *          GET ---  $this->get();
 *          POST --- $this->post();
 *          PUT --- $this->put();
 *         DELETE --- $this->delete();
 */
require(APPPATH.'libraries/Mobile_Controller.php');
class User_files extends Mobile_Controller
{
    private $_user_info;

    public function __construct()
    {

        parent::__construct();

        $services = array(
            "login_service",
            "user_info_service",
            "user_files_service",
            "user_policies_service"
        );

        $this->load->service($services);
        //获取登录人的信息
        $this->_user_info = $this->login_service->get_user_info();
    }

    /**
     * ::上传头像
    */
    public function avatar_post()
    {
        $update_image = $this->user_info_service->upload_face($this->_user_info['id'],$this->_user_info['image'],'avatar');

        if ($update_image === FALSE)
        {
            return $this->common_response($this->user_info_service);
        }
        else
        {
            $update = $this->user_info_service->update_user_info($this->_user_info['id'], array('image' => $update_image['img']));
            if ($update === FALSE)
            {
                return $this->common_response($this->user_info_service);
            }
            else
            {
                $this->login_service->refresh_user_info('image', $update_image['img']);
                return $this->common_response(0, NULL, array('data' => array('avatar' => site_url($update_image['img']))));
            }
        }
    }




    /**
     * ::访问控制，检查文件或者文件夹是否受限
     */
    public function access_denied_get() {
        $file_id = trim($this->input->get('files'));
        $folder_id = trim($this->input->get('folders'));

        if (empty($file_id) && empty($folder_id)) return $this->common_response(1003);

        $file_ids = empty($file_id) ? '' : explode(',', $file_id);
        $folder_ids = empty($folder_id) ? '' : explode(',', $folder_id);
        $children = FALSE;
        $data = $this->user_policies_service->get_data_info($this->_user_info['id'], $file_ids, $folder_ids, $children);

        //判断是否有文件
        if (empty($data['files'])) {
            return $this->common_response(7103);
        }
        $ac = FALSE;  //是否存在禁止文件/文件夹开关
        $result = $denied_ids = array();
        foreach ($data as $keys => $values) {
            foreach ($values as $key => $value) {
                if ($value['access_denied'] == 1) {
                    if (!$ac) $ac = TRUE; //如果ac本来是false则true
                    $denied_ids[$keys][] = $value['id'];
                }
                $value['uid'] = $this->_user_info['id'];
                $result[$keys][] = $value;
            }
        }
        if ($ac) {
            return $this->common_response(7007, '', array('data' => implode(',', $denied_ids['files'])));
        } else {
            return $this->common_response(0);
        }
    }

    /**
     * 更新文件权限
     */
    public function access_denied_put() {
        $files = trim($this->put('files'));
        //$folders = trim($this->put('folders'));
        $denied = (int)trim($this->put('denied'));
        if (empty($files)){
            return $this->common_response(1003);
        }

        //if (empty($files) && empty($folders)) return $this->common_response(1003);

        //$files = $folders = array();
        /*
        if (!empty($files)) {
            $files = explode(",",$files);
        }
        if(!empty($folders)) {
            $folders = explode(",",$folders);
        }
        */

        $all = FALSE;
        $files = explode(",",$files);
        $folders = array();

        $edit = $this->user_files_service->update_access_denied($this->_user_info['id'], $files, $folders, $denied, $all);
        if ($edit !== FALSE) {
            return $this->common_response(0);
        } else {
            return $this->common_response($this->user_files_service);
        }
    }

    /**
     * ::访问控制
     *
     */
    public function access_control_put()
    {
        $file_id = trim($this->put('files'));
        //$folder_id = trim($this->put('folders'));  //文件夹不可设置策略
        $folder_id = array();

        if (empty($file_id) && empty($folder_id)) return $this->common_response(1003);

        $file_ids = empty($file_id) ? array() : explode(',', $file_id);
        $folder_ids = empty($folder_id) ? array() : explode(',', $folder_id);
        //如果直接分享则需要判断子孙目录的文件TRUE,如果是访问控制分享则FALSE
        $children = empty($shared) ? FALSE : TRUE;
        //var_dump(array('a'=>$file_ids,'b'=>$folder_ids));exit;
        $data = $this->user_policies_service->get_data_info($this->_user_info['id'], $file_ids, $folder_ids, $children);
        //var_dump(array($data['files']));exit;
        $ac = FALSE;  //是否存在禁止文件/文件夹开关
        $result = $denied_ids = array();
        foreach ($data as $keys => $values)
        {
            foreach ($values as $key => $value)
            {
                if ($value['access_denied'] == 1)
                {
                    if (!$ac) $ac = TRUE; //如果ac本来是false则true
                    $denied_ids[$keys][] = $value['id'];
                }
                $value['uid'] = $this->_user_info['id'];
                $result[$keys][] = $value;
            }
        }
        if ($ac)
        {
            return $this->common_response(7007, '', array('data' => implode(',', $denied_ids['files'])));
        }

        $life_span = $this->put('life_span');
        if (! empty($life_span))
        {

            if ((int)$life_span < time()) {

                //var_dump(array('a'=>time()));exit;

                //var_dump(array('a'=>(int)$life_span));exit;
                return $this->common_response(1020);
            }
        }

        $getTime = $this->put('life_span');
        if (! empty($getTime) && $getTime < time()) {
            $getTime = time();
        }
        //设置查阅密码
        $invar['read_pwd'] = $this->put('read_pwd');

        $invar['life_span'] = $getTime;
        $invar['open_counter'] = $this->put('open_counter');
        //过期是否删除
        $invar['delete_after_expired'] = $this->put('delete_after_expired');


        $arr_avgs = array();
        foreach ($invar as $k => $v)
        {
            if ($k != "read_pwd")
            {
                $v = (int)$v;

            }
            $arr_avgs[] = array('des' => $k, 'value_set' => $v);
        }
        if(empty($result['folders'])&&empty($result['files']))
        {
            $this->common_response(1003);
        }
        else
        {
            /**
             * 添加策略与轨迹
             * @param $file 文件
             * @param $type 类型 1为文件,则添加轨迹; 2为文件夹,不添加轨迹
             * @param $n_policy array()
             */

            if (isset($result['files']))
            {
                foreach ($result['files'] as $v)
                {
                    $this->user_policies_service->add_policies($v, 1, $arr_avgs);
                }
            }
            else
            {
                foreach ($result['folders'] as $v)
                {
                    $this->user_policies_service->add_policies($v, 2, $arr_avgs);

                }
            }
            $this->common_response(0);
        }

    }



    /**
     * ::文件分享
     *
    */
    public function file_policy_put()
    {
        $file_id = trim($this->put('files'));
        $folder_id = trim($this->put('folders'));
        $name = trim($this->put('name')) ;
        $shared = trim($this->put("share"));
        if (empty($file_id) && empty($folder_id))
        {
            return $this->common_response(1003);
        }
        $file_ids = empty($file_id) ? array() : explode(',', $file_id);
        $folder_ids = empty($folder_id) ? array() : explode(',', $folder_id);
        //var_dump(array('a'=>$file_ids));exit;

        //如果直接分享则需要判断子孙目录的文件TRUE,如果是访问控制分享则FALSE
        $children = empty($shared) ? FALSE : TRUE;
        $data = $this->user_policies_service->get_data_info($this->_user_info['id'], $file_ids, $folder_ids, $children);

        //
        $ac = FALSE;  //是否存在禁止文件/文件夹开关
        $result = $denied_ids = array();
        foreach ($data as $keys => $values) {
            foreach ($values as $key => $value)
            {
                if ($value['access_denied'] == 1)
                {
                    if (!$ac) $ac = TRUE; //如果ac本来是false则true
                    $denied_ids[$keys][] = $value['id'];
                }
                $value['uid'] = $this->_user_info['id'];
                $result[$keys][] = $value;
            }
        }

        //无文件
        if (empty($result)) return $this->common_response(7103);

        /*if ($ac)
        {
            return $this->common_response(7007, '', array('data' => implode(',', $denied_ids['files'])));
        }*/
        //有文件但全部受限
        $list_file_ad=array();
        if(isset($result['files'])){
            $list_file_ad = Common::array_column($result['files'], "access_denied");
        }


        //array_unique
        if (! in_array("0", $list_file_ad))
        {

            return $this->common_response(7103);
        }

        $this->load->service('share_service');

        //把文件ID列表和文件夹ID列表组合成  "3||54,22,13"格式  文件id,文件id||文件夹id,文件夹id
        $list_str = $this->share_service->create_file_str($file_ids, $folder_ids);
        //把链接符 通过md5不可逆方式加密
        $list_md5 = md5($list_str);  //连接符md5加密

        //查看数据库中有没有相同的分享，根据$list_md5查询
        $res = $this->share_service->check_share_code($list_md5);

        //var_dump(array('a'=>$res));exit;

        $list_hash = Common::time33($list_md5);

        //获取分享链接的名字,没有默认为“【易控文件分享】”
        $name = empty($name) ? $this->lang->line('share_name') : $name;

        //已经分享过
        if (count($res) > 0) {
            unset($res['id']);
            $res['name'] = $name;
            $res['share_link'] = site_url('/s/'.$res['share_code']);
            return $this->common_response(0, '', array('data' => $res));
        }

        //生成分享码
        $share_codes = $this->share_service->short_code($list_str.time(), FALSE);
        $share_code = $share_codes[0];
        //获取数据整合到变量$share中，方便添加到u_share_link表中
        $share = array(
            "name" => $name, //$list_name
            "share_code" => $share_code,
            'share_code_hash' => Common::time33($share_code),
            'list_md5' => $list_md5,
            'list_md5_hash' => $list_hash,
            'password' => '',
            'uid' => $this->_user_info['id'],
            "creation_ts" => time()
        );

        //获取数据整合到变量$slist中，方便添加到u_share_list表中
        $slist = array();
        if (! empty($file_ids)) {

            foreach ($file_ids as $val) {
                $slist[] = array('ctype' => 1, 'c_uuid' => $val);
            }
        }

        if (! empty($folder_ids)) {
            foreach ($folder_ids as $val) {
                $slist[] = array('ctype' => 2, 'c_uuid' => $val);
            }
        }

        //添加分享
        //var_dump(array('a'=>$share,'b'=>$slist));exit;
        //分别往数据库u_share_link和u_share_list添加数据,添加成功返回true
        $flag = $this->share_service->add($share, $slist);
        if (! $flag) return $this->common_response(1017);
        //更新文件的分享开关u_files.shared
        if (! empty($file_ids)) {
            $this->share_service->update_shared_batch($this->_user_info['id'], $file_ids);
        }

        if (! empty($folder_ids)) {
            $this->share_service->update_files_shared($this->_user_info['id'], $folder_ids);
        }




        $cb = array(
            'name' => $name,
            'password' => '',
            'share_code' => $share_code,
            'share_link' => site_url('/s/'.$share_code)
        );

        return $this->common_response(0, '', array('data' => $cb));
    }





    /**
     * ::属性
    */
    public function att_list_get()
    {
        $file_id = trim($this->input->get('id', TRUE));
        $type = (int)$this->input->get("type", TRUE); //0文件,1文件夹
        if (empty($file_id)) return $this->common_response(1003);

        $file = $this->user_policies_service->get_policy($this->_user_info['id'], $type, $file_id);
        //var_dump(array('a'=>$file));exit;
        if(! $file) return $this->common_response(1003);

        $file_policies = json_decode($file['data'], TRUE);
        $retArr = array(
            'read_pwd' => NULL,
            'life_span' => NULL,
            'open_counter' => NULL,
            'delete_after_expired' => NULL
        );
        if (NULL !== $file_policies) {
            foreach ($file_policies as  $index => $file_policy){
                if($file_policy['des'] == 'read_pwd') {  //密码
                    $retArr['read_pwd'] = $file_policy['value_set'];

                }else{ //其它参数
                    $retArr[$file_policy['des']] = $file_policy['value_set'];
                }
            }
        }
        if($type===1)
        {
            $retArr["file_count"]=$this->user_policies_service->get_folder_file_count($this->_user_info['id'],$file_id);
        }

        return $this->common_response(0, '', array('data' => $retArr));
        /*
        //获取文件夹或者文件id
        $f_ids  = $this->input->post('f_ids');
        if (empty($f_ids)) return $this->common_response(1003);
        //type=1为文件夹，2为文件
        $f_type = $this->input->post('f_type');
        //获取登录人的信息
        $old_uin = $this->login_service->reload_user_info();
        $data=$this->user_policies_service->get_attribute($f_ids,$old_uin['id']);

        if($f_type==='2')
        {

            $file = $this->user_policies_service->get_policy($this->_user_info['id'], 0, $f_ids);
            if(! $file) return $this->common_response(1003);

            $file_policies = json_decode($file['data'], TRUE);
            $data = array(
                'read_pwd' => NULL,
                'life_span' => NULL,
                'open_counter' => NULL,
                'delete_after_expired' => NULL
            );
            if (NULL !== $file_policies) {
                foreach ($file_policies as  $index => $file_policy){
                    if($file_policy['des'] == 'read_pwd') {  //密码
                        $retArr['read_pwd'] = $file_policy['value_set'];

                    }else{ //其它参数
                        $data[$file_policy['des']] = $file_policy['value_set'];
                    }
                }
            }
        }
        return $this->common_response(0,'',array('data'=>$data));*/
    }



    /**
     * :: 文件轨迹
    */
    public function file_trace_get() {
        $file_id = (int)$this->input->get('id', TRUE);
        $page = (int)$this->input->get('page', TRUE);
        $total = (int)$this->input->get('total', TRUE);
        //如果没有轨迹则参数错误
        if (empty($file_id)) return $this->common_response(1003);
        $this->load->service('file_trace_service');
        $get_where = array("hidden" => 0, "relation" => 0);
        $get_fields = "id,actor,event,ts,unsafe,hidden,file_id,actor_ip,actor_city";
        //轨迹翻页

        $limit_num = empty($total) ? $this->config->item('file_trace_num') : $total;
        $limit = array($page * $limit_num, $limit_num);
        $dates_data = $this->file_trace_service->get_traces($file_id, $get_where,"ts","desc", $get_fields, $limit);
        //如果没有轨迹则参数错误


        if (empty($dates_data)) return $this->common_response(1003);

        if(! empty($dates_data['rows'])) {
            $traces_data = array();
            $date_tag = 0;
            foreach ($dates_data['rows'] as $key => $val) {
                $date_tmp = date('Ymd', $val['ts']);
                if ($date_tmp !== $date_tag) {
                    $val['ts_f'] = '1';
                    $date_tag = $date_tmp;
                } else {
                    $val['ts_f'] = '0';
                }

                if ($val['event'] == Traces::EVENT_SCREEN_SHOT_FILE) {
                    $val['name'] = trim($this->file_trace_service->get_event_param_name($val['event'], $val['actor']));
                } else {
                    $val['name'] = $this->file_trace_service->get_event_name($val['event']);
                }
                $traces_data[] = $val;
            }
            return  $this->common_response(0, '', array('data' => $traces_data));
        } else {
            return $this->common_response(1018);
        }
    }



    /**
     * ::删除文件或者文件夹
     */
    public function files_delete()
    {
        //根据文件夹或者文件ID删除
        $files = $this->delete('files', TRUE);
        $folders = $this->delete('folders', TRUE);
        if (empty($files) && empty($folders))
        {
            return $this->common_response(1003);
        }

        $files = empty($files) ? array() : explode(',', $files);
        $folders = empty($folders) ? array() : explode(',', $folders);
        $this->user_files_service->delete($this->_user_info['id'], $files, $folders);
        $space = $this->user_info_service->get_format_space($this->_user_info['id']);
        return $this->common_response(0,NULL,array('space'=>$space));
    }







    /**
     *  ::文件列表
     *  获取文件列表，根据参数不同，获取对应的文件
     *  包含所有文件，已分享、已下载、已过期
     *
     *
     */
     public function file_list_get()
    {
        //$state 0：表示所有文件，1：已分享，2已下载，3已过期
        $state = intval($this->input->get('state', TRUE));

        //var_dump(array('a'=>$state));exit;
        //获取文件夹ID
        $folder_id = intval($this->input->get('pid', TRUE));
        $page = intval($this->input->get('page', TRUE));
        $total = intval($this->input->get('limit', TRUE));
        $limit_num = empty($total) ? 0 : $total;
        $limit = $limit_num>0?array($page * $limit_num, $limit_num):false;
        if($state===0)
        {
            $list = $this->user_files_service->get_list($this->_user_info['id'], $folder_id,"","creation_ts","desc",array("deleted"=>0),"",$limit);

            $folders = (array)$list['folders'];
            $folder_tmp = array();
            foreach ($folders as $key => $value) {
                $value['size'] = "0";
                $value['ext_name'] = "0";
                $folder_tmp[] = $value;
            }
            if (count($folder_tmp) > 0) {
                $folders = $folder_tmp;
            }

            $result = array_merge($folders, (array)$list['files']);
        }
        else if($state===1)
        {

            $files = $this->user_files_service->get_share_file_list($this->_user_info['id'], false, "", "creation_ts", "desc",array("deleted"=>0),"",$limit);
        }
        else if($state===2)
        {
            $files = $this->user_files_service->get_downloaded_file_list($this->_user_info['id'], false, "", "creation_ts", "desc",array("deleted"=>0),"",$limit);
        }
        else if($state===3)
        {
            //var_dump(array('a'=>$state));exit;
            $files = $this->user_files_service->get_exp_file_list($this->_user_info['id'], false, "", "creation_ts", "desc",array("deleted"=>0),"",$limit);
        }
        else
        {
            return $this->common_response(1003);
        }

        if($state===0)
        {
            $folder_info = $folder_id>0 ? $this->user_files_service->get_path_info($this->_user_info['id'],$folder_id) :null;
            if($folder_info===FALSE)
            {
                Common::ajax_return($this->user_files_service);
            }
            return $this->common_response(0, '', array('data' => $result,"path_info"=>$folder_info));
        }
        else
        {
            return $this->common_response(0, '', array('data' => (array)$files['rows']));
        }

    }


    /**
     * ::意见反馈
     *
     */
    public function feedback_post()
    {
        $content = trim($this->input->post('content', TRUE));
        if (empty($content)) return $this->common_response(1003);

        $this->load->service("feedback_service");

        if ($this->login_service->is_login())
        {
            $userinfo[] = 'Uid: '.$this->login_service->get_user_info('id');
            $nickname = $this->login_service->get_user_info('nickname');
            if (! empty($nickname))
            {
                $userinfo[] = 'User: ' . $nickname;
            }

            $this->feedback_service->userinfo = $userinfo;
            $email = $this->login_service->get_user_info('email');
            if (empty($email))
            {
                $mobile = $this->login_service->get_user_info('mobile');
                if (! empty($mobile)) $email = $mobile."@mobile.com";
            }
            if (! empty($email))
            {
                $contact['email'] = $email;
            }
        }
        else
        {
            $contact = "Guest@mobile.com";
        }

        $res = $this->feedback_service->add($content, $contact);
        if (! $res)
        {
            return $this->common_response($this->feedback_service);
        }
        return $this->common_response(0);
    }

    /**
     * ::帮助中心
     */




    /**
     * ::退出
     */
    public function logout_get() {
        $this->login_service->logout();
        $this->common_response(0);
    }

    /**
     * 获取打包
     */
    public function pack_percent_get()
    {
        $sess_data = $this->session->userdata("PACKET_LIST");
        //$test = !is_array($sess_data) || empty($sess_data)?FALSE:TRUE;
        //本地调试服务器处理
        $id = $this->input->get("id",TRUE);
        $space = array();
        if(ENVIRONMENT=="development")
        {
            if(!is_array($sess_data) || empty($sess_data))
            {
                $sess_data=array();
            }
            $data=array();
            $step = 20;
            //var_dump($sess_data);
            $dpercent = $step;
            if(empty($id))
            {
                Common::ajax_return(1003);
            }
            else if(!isset($sess_data[$id]) || !isset($sess_data[$id]['percent']))
            {
                Common::ajax_return(1003);
            }
            else if($sess_data[$id]['percent']>=100 || $sess_data[$id]['percent']+20>=100)
            {
                $dpercent = 100;
                /*$data = $this->user_files_service->get_all_file_info_by_guid($id,NULL,NULL,NULL,"id,guid,name,size,type,ext_name,creation_ts,modify_ts,folder_id,source_guid,access_denied",NULL,NULL);*/
                //var_dump($id);exit;
                $params = $sess_data[$id]['params'];
                $data = $this->user_files_service->add_file($params['uid'],$params['name'],$params['size'],$params['mime_type'],$params['md5'],$params['source_guid'],$params['folder_id'],$params['guid']);
                if($data===FALSE)
                {
                    Common::ajax_return($this->user_files_service);
                }
                $add_sec = $this->user_files_service->add_secure_file($data['id'],$params['size'],1,Common::uniqid(),Common::uniqid(),Common::uniqid());
                if($add_sec===FALSE)
                {
                    return Common::ajax_return($this->user_files_service);
                }
                $default_path = $this->config->item("default_upload_path")."file/";
                if(!is_dir($default_path))
                {
                    @mkdir($default_path,0777,true);
                }
                $save_path = $default_path.$params['source_guid'].".tmp";

                if($data['source_guid']==$params['source_guid'])
                {
                    copy($params['file_path'],$save_path);
                }
                if(file_exists($params['file_path']))
                {
                    @unlink($params['file_path']);
                }
                unset($sess_data[$id]);
                $space = $this->user_info_service->get_format_space($this->_user_info['id']);
            }
            else
            {
                $sess_data[$id]['percent'] += $step;
                $dpercent = $sess_data[$id]['percent'];
            }

            $this->session->set_userdata("PACKET_LIST",$sess_data);

            Common::ajax_return(0,NULL,array("percent"=>$dpercent,"id"=>$id,"data"=>$data,"space"=>$space),FALSE);
        }
        //线上服务器处理
        else
        {

            $redis = new Redis();
            $con = $redis->connect($this->config->item("host","redis"), $this->config->item("port","redis"), $this->config->item("timeout","redis"));
            if(!$con)
            {
                Common::ajax_return(1019);
            }
            //$this->redis->setex("testtest",10,"hahahah");
            $redis_data =  $redis->get($id);
            $data=json_decode($redis_data,true);
            if(!$data)
            {
                Common::ajax_return(1019);
            }
            if(isset($data['error_code']) && $data['error_code']>0)
            {
                Common::ajax_return($data['error_code']);
            }
            $space = $this->user_info_service->get_format_space($this->_user_info['id']);
            Common::ajax_return(0,NULL,array("percent"=>$data['percent'],"id"=>$id,"data"=>$data['data'],"space"=>$space),FALSE);
        }

    }


}
